package welcome;

import java.io.File;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import tools.HttpUtils;
import tools.MyProgressDialog;
import tools.PackageUtils;

import com.email.content.EmailDetailActivity;
import com.example.logindesign.LoginActivity;
import com.example.logindesign.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class CheckVersionActivity extends Activity {
	private static final String NAMESPACE = "http://tempuri.org/";
	private static final String ENDPOINT = "http://192.168.1.198:1536/CommunitySystemsicWsWF.asmx";
	private String methodName, soapAcion;

	// 两个工具类 获取当前已经装载在手机的apk包的信息，http连接下载apk
	private PackageUtils packageUtils;
	private HttpUtils httpUtils;

	private ProgressDialog progressDialog;
	private String apkUrl = "";
	private String oldVersion, newVersion;
	// 询问是否更新对话框
	private AlertDialog.Builder builder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_checkversion);

		//
		builder = new AlertDialog.Builder(CheckVersionActivity.this);
		builder.setCancelable(false);
		builder.setTitle("提示");
		builder.setMessage("有新版本，是否要下载更新");
		builder.setPositiveButton("立即更新", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				new DownloadAPK().execute(apkUrl);
			}
		});
		builder.setNegativeButton("稍后再说", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				// 跳转到欢迎界面
				skipWelcomeActivity();
			}
		});

		packageUtils = new PackageUtils(this);
		progressDialog = new ProgressDialog(this);
		oldVersion = packageUtils.getVersionName();
		// 获取版本
		new CheckVersionTask().execute();

	}

	/**
	 * 下载apk
	 * 
	 * @author Administrator
	 * 
	 */
	public class DownloadAPK extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog.setTitle("提示");
			progressDialog.setMessage("程序下载中,请稍等......");
			progressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String downloadPath = httpUtils.downloadAPK(params[0]);
			return downloadPath;
		}

		@Override
		protected void onPostExecute(String downloadPath) {
			// TODO Auto-generated method stub
			super.onPostExecute(downloadPath);
			progressDialog.dismiss();

			// 判断下载路径是否为空
			if (downloadPath != null) {
				// 重置sharedpreference
				// 记录是否为首次启动
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"fisrstUse", Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = mySharedPreferences.edit();
				// 获取要保持信息，进行存储
				editor.putBoolean("isFirstUse", false);
				// 提交事务
				editor.commit();

				// 直接安装
				Uri uri = Uri.fromFile(new File(downloadPath));
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri,
						"application/vnd.android.package-archive");
				startActivity(intent);
			}
		}

	}

	/**
	 * 对比版本，提示是否下载
	 * 
	 * @author Administrator
	 * 
	 */
	public class CheckVersionTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog.setTitle("提示");
			progressDialog.setMessage("检查版本中,请稍等......");
			progressDialog.show();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String result = getVersionCode();
			String finallyResultString = jsonFormat(result);
			return finallyResultString;
		}

		@Override
		protected void onPostExecute(String finallyResultString) {
			progressDialog.dismiss();
			if (finallyResultString.equals("success")) {
				// 判断下版本差异
				if (packageUtils.isUpgradeVersionName(oldVersion, newVersion)) {
					// 弹出对话框
					builder.create().show();
				} else {
					// 跳转到欢迎界面
					skipWelcomeActivity();
				}
			} else {
				// 跳转到欢迎界面
				skipWelcomeActivity();
			}
		}
	}

	/**
	 * 跳转到欢迎页面
	 */
	private void skipWelcomeActivity() {
		Intent welcomeIntent = new Intent();
		welcomeIntent.setClass(CheckVersionActivity.this,
				WelcomeActivity2.class);
		CheckVersionActivity.this.startActivity(welcomeIntent);
		CheckVersionActivity.this.finish();
	}

	/**
	 * 得到versionCode
	 * 
	 * @return
	 */
	private String getVersionCode() {
		// TODO Auto-generated method stub
		String resultString = "";
		methodName = "get_VersionCode";
		soapAcion = "http://tempuri.org/get_VersionCode";
		SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soapObject);
		envelope.dotNet = true;
		HttpTransportSE transportSE = new HttpTransportSE(ENDPOINT);
		try {
			transportSE.call(soapAcion, envelope);
			if (envelope.getResponse() != null) {
				SoapObject object = (SoapObject) envelope.bodyIn;
				resultString = object.getProperty(0).toString();
				Log.e("webservice取得", resultString);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("IOException", e.getMessage());
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("XmlPullParserException", e.getMessage());
		}
		return resultString;
	}

	/**
	 * 解析json数据
	 * 
	 * @return
	 */
	private String jsonFormat(String resultString) {
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(resultString);
			JSONObject jsonObject = jsonArray.optJSONObject(0);
			if (jsonObject.optString("Code").equals("1")) {
				jsonObject = jsonArray.optJSONObject(0);
				newVersion = jsonObject.optString("versionCode");
				apkUrl = jsonObject.optString("apkUrl");
				return "success";
			} else {
				return "fail";
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "fail";
	}

}
